package com.mgetwd.springbootweb.Interceptor;


import cn.hutool.core.util.ObjectUtil;
import com.mgetwd.springbootweb.dict.BifDict;
import com.mgetwd.springbootweb.config.RedisHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;


@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisHelper redisHelper;

    //在业务处理之前调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截用户是否之前登陆过
        String sk = request.getHeader("token");
        Object token = redisHelper.get(sk);
        if (ObjectUtil.isNotNull(token)) {
            //token 只存在30分钟,
            redisHelper.expireKey(BifDict.TOKEN, 30, TimeUnit.MINUTES);
            return true;
        } else
            log.error("请带token");
        return false;
    }

    //在业务处理请求完成之后, 生成视图之前viewResolver执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //在dispatcherServelt完全处理请求之后调用, 可用于清理资源
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
